#!/usr/bin/python -itt
import os.path
import sys
import numpy as np

import logging
import logging.config

scriptpath = os.path.dirname(os.path.realpath(__file__))
logging.config.fileConfig(scriptpath+'/logging.conf')
logger = logging.getLogger('turnIntoZenit')


def turn_photons_into_zenith( thedict, 
        dictname='photonData', 
        pos_key='ground_dir', 
        dir_key='ground_pos',
        new_pos_key='ground_pos_turned', 
        new_dir_key='ground_dir_turned'):
    
    logger.debug("turn_photons_into_zenith starting up")
    
    from Turnable import make_axis_rotation_matrix
    make_matrix = make_axis_rotation_matrix
    
    data = thedict[dictname]
    
    dir = data[pos_key]
    pos = data[dir_key]
    
    logger.debug("photons to be turned: %d" % pos.shape[0])
    # in order to turn all photons such that they appear to come ftom zenith
    # I have to find the mean direction, where they come from, 
    # since this is not stored inside the corsika file and thus not stored somewhere
    # in the run-objects headers :-(
    #
    # Please note: I could first calculate the theta and phi angles of all 
    # direction vectors of all photons and then take their mean, but this 
    # seems not to be a good idea. I had problems doing this, when the photons
    # where already nearly coming from zenith. 
    # Because in such a case, their phi angles can have almost any value
    # their mean is not very accurate of course.
    # So instead I decided to calculate the mean of all direction vectors first
    # and then take theta and phi of this single vector.
    
    mean_dir = dir.mean(axis=0)
    theta = np.arccos( mean_dir[2] )
    phi = np.arctan2( mean_dir[1] , mean_dir[0] )
    
    ################### actual turning takes place here  ###############
    Rz = make_matrix( [0,0,1], -1.*phi )
    Ry = make_matrix( [0,1,0], -1.*theta )
    Rzy  = np.dot(Rz,Ry)
    ####################################################################

    dir_after_turn = np.dot(dir, Rzy)
    pos_after_turn = np.dot(pos, Rzy)
    
    data[new_pos_key] = pos_after_turn
    data[new_dir_key] = dir_after_turn
    
    return thedict


